package com.rzx.mybackend.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * OssUtil
 *
 * @author renzhexian
 * @date 2025/7/17
 */


@Component
@Slf4j
public class OssUtil {

    @Value("${aliyun.oss.endpoint}")
    private String ENDPOINT;

    @Value("${aliyun.oss.access-key-id}")
    private String ACCESS_KEY_ID;

    @Value("${aliyun.oss.access-key-secret}")
    private String ACCESS_KEY_SECRET;

    @Value("${aliyun.oss.bucket-name}")
    private String BUCKET_NAME;

    /**
     * 上传文件到OSS
     * @param file 上传的文件
     * @param folder 存储目录（如 "images/"）
     * @return 文件访问URL
     */
    public String uploadFile(MultipartFile file, String folder) throws IOException {
        // 参数校验
        if (file == null || file.isEmpty()) {
            log.warn("上传文件为空");
            return null;
        }

        if (folder == null || folder.trim().isEmpty()) {
            log.warn("存储目录为空");
            return null;
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || originalFilename.isEmpty()) {
            log.warn("原始文件名为空");
            return null;
        }

        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString().replace("-", "") + extension;

        // 构造完整路径
        String objectName = folder + "/" + fileName;
        log.info("开始上传文件，原始文件名：{}，目标路径：{}", originalFilename, objectName);

        OSS ossClient = null;
        try {
            // 创建OSSClient实例
            ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
            log.debug("OSS客户端创建成功");

            // 获取文件输入流
            InputStream inputStream = file.getInputStream();

            // 创建PutObjectRequest对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, objectName, inputStream);

            // 上传文件
            ossClient.putObject(putObjectRequest);
            log.info("文件上传成功，文件路径：{}", objectName);

            // 返回文件访问URL
            String fileUrl = "https://" + BUCKET_NAME + "." + ENDPOINT + "/" + objectName;
            log.info("文件访问URL生成成功：{}", fileUrl);
            return fileUrl;
        } catch (OSSException oe) {
            log.error("OSS异常：错误消息={}, 错误代码={}, Request ID={}, Host ID={}",
                    oe.getErrorMessage(), oe.getErrorCode(), oe.getRequestId(), oe.getHostId());
        } catch (ClientException ce) {
            log.error("客户端异常：错误消息={}", ce.getMessage());
        } catch (Exception e) {
            log.error("文件上传异常：", e);
        } finally {
            if (ossClient != null) {
                try {
                    ossClient.shutdown();
                    log.debug("OSS客户端关闭成功");
                } catch (Exception e) {
                    log.warn("OSS客户端关闭异常：", e);
                }
            }
        }
        return null;
    }
}